#include "EditorMenu.h"
#include "Util.h"
#include "Application.h"

EditorMenu::EditorMenu(Application* app) : Menu(app)
{
    setBackgroundImage("editor_menu.png");
    mapList = new WidgetList(250,80,300,400,20);
    newMapButton = new WidgetButton(this, 250,485,147,40, "New / Edit", 30);
    backButton = new WidgetButton(this, 403, 485, 147, 40, "Back", 30);
    addWidget(mapList);
    addWidget(newMapButton);
    addWidget(backButton);
    subEngine = NULL;
    newMap = new NewMapMenu(app);
}

void EditorMenu::onLaunch()
{
    std::vector<std::string> maps;
    std::vector<std::string> subs;
    Util::getDirectories(maps, ".");
    for(int i=0; i<maps.size(); i++)
    {
        Util::split(maps[i], '.', subs);
        if(subs[subs.size() - 1] == "map")
            mapList->add(maps[i]);

        subs.clear();
    }
}

void EditorMenu::onEvent(sf::Event* event)
{
    if(subEngine == NULL)
    {
        Menu::onEvent(event);
    }
    else
    {
        subEngine->onEvent(event);
    }
}

void EditorMenu::onRender(sf::RenderWindow* window)
{
    if(subEngine == NULL)
    {
        Menu::onRender(window);
    }
    else
    {
        subEngine->onRender(window);
    }
}

void EditorMenu::onTick()
{
    if(subEngine == NULL)
    {

    }
    else
    {
        subEngine->onTick();

        if(subEngine->terminated())
        {
            closeSubMenu();
        }
    }
}

void EditorMenu::onClose()
{
    mapList->clear();
}

void EditorMenu::openSubMenu(Engine* e)
{
    if(subEngine != NULL)
        closeSubMenu();

    subEngine = e;
    subEngine->onLaunch();
}

void EditorMenu::closeSubMenu()
{
    if(subEngine != NULL)
    {
        subEngine->onClose();
        subEngine = NULL;
    }
}

void EditorMenu::onButtonPressed(WidgetButton* button)
{
    if(button == newMapButton)
        openSubMenu(newMap);

    if(button == backButton)
        app->setActiveMode(Application::MAIN_MENU);
}

EditorMenu::~EditorMenu()
{
    //dtor
}
